<?php

class Cache{
	var $cacheDir;

	protected $cacheString;
	protected $depth;

	function __construct(){
		$this->cacheDir = D_P.'data/cache/';
		if(!is_writeable($this->cacheDir)) throwError('cachedircannotwrite');
	}

	function Cache(){
		$this->__construct();
	}

	function config()
	{
		global $db;
		$cache="<?php\n";
		$cache_array = "\$very = array(\n";
		$rs = $db->query("SELECT * FROM cms_config WHERE db_name LIKE 'db_%'");
		while ($sitedb = $db->fetch_array($rs)) {
			//if($sitedb['db_name']=='discate')
			$sitedb['db_value']=addslashes($sitedb['db_value']);
			//$cache.="\$$sitedb[db_name]=\"$sitedb[db_value]\";\n";
			$key_name = substr($sitedb[db_name],3);
			$cache_array.="\t'$key_name'=>'$sitedb[db_value]',\n";
		}
		$cache_array.=");\n\$restype = array(\n";
		$rs = $db->query("SELECT * FROM cms_restype ORDER BY typeid");
		while ($res = $db->fetch_array($rs))
		{
			$cache_array .= "\t" . $res['typeid'] . "=>array(\n";
			$cache_array .= "\t\t'typeid'=>'$res[typeid]',\n";
			$cache_array .= "\t\t'typename'=>'$res[typename]',\n";
			$cache_array .= "\t\t'typeext'=>array(";
			$extArr = explode(',', $res['typeext']);
			$String = array();
			foreach ($extArr as $ext)
			{
				if (empty($ext)) continue;
				$String[] = "'$ext'";
			}
			$cache_array .= implode(',', $String);
			$cache_array .= ")\n),\n";
		}
		$cache_array .= ");\n";

		$cache_array .= "\$fileicon = array(";
		
		$fp = opendir(R_P . 'images/admin/file');
		//$icon = array();
		while ($filename = readdir($fp)) {
			if($filename=='..' || $filename=='.') continue;
			$icon = current(explode('.', $filename));
			$cache_array .= "'$icon',";
		}
		$cache_array .= ");\n";
		
		$cache.=$cache_array."?>";
		writeover($this->cacheDir.'config.php',$cache);
	}

	/**
	 * 用户组缓存
	 *
	 */
	function group()
	{
		global $db;
		$rs = $db->get_array("SELECT * FROM cms_group");
		$this->saveArray($rs, 'group', 'groupid');
		writeover($this->cacheDir . 'group.php', "<?php\n" . $this->cacheString . "\n?>");
	}

	/**
	 * 服务器缓存
	 *
	 */
	function server()
	{
		global $db;
		$rs = $db->get_array("SELECT * FROM cms_server");
		$this->saveArray($rs, 'server', 'serverid');
		writeover($this->cacheDir . 'server.php', "<?php\n" . $this->cacheString . "\n?>");
	}


	function cate(){
		global $db,$very;
		$cache = "<?php\n\$catedb=array(\n";
		$rs = $db->query("SELECT * FROM cms_category ORDER BY taxis DESC");
		$total = $CATE = array();
		
		/* 暂时解决二级目录下的内容数量统计问题 */
		while ($cateinfo = $db->fetch_array($rs)) { //作数量统计
			
			if ($cateinfo['up']) {
				$total[$cateinfo['up']] += $cateinfo['total'];
			}
			$total[$cateinfo['cid']] += $cateinfo['total'];
			
			$CATE[$cateinfo['cid']] = $cateinfo;
		}
		/* end */
		
		foreach ($CATE as $key => $catedb) {
		//while ($catedb = $db->fetch_array($rs)) {
			$cache.="\t'$catedb[cid]'=>array(\n";
			if($catedb['link']){
				$catedb['listurl']=$catedb['link'];
			}else{
				if($catedb['listpub']){
					$catedb['listurl']=$very['htmdir'].'/'.$catedb['listurl'];
				}else{
					$catedb['listurl']='list.php?cid='.$catedb['cid'];
				}
			}
			$catedb['total'] = $total[$key];
			$cache.=$this->getCache($catedb);
			/*
			foreach ($catedb as $key=>$value){
			!is_numeric($value) && $value = addslashes($value);
			$cache.="\t\t'$key'=>'$value',\n";
			}
			*/
			$cache.="\t),\n";
		}
		$cache.=");\n?>";
		writeover($this->cacheDir.'cate.php',$cache);
	}

	function field(){
		global $db,$moduledb;
		$fielddb = array();
		$fieldcache = "\$fielddb=array(\n";
		$rs = $db->query("SELECT * FROM cms_module");
		$mids = array();
		while ($m = $db->fetch_array($rs)) {
			$mids[]=$m['mid'];
			$mid = $m['mid'];
			$fielddb[$mid]=array();
		}
		$rs = $db->query("SELECT * FROM cms_field ORDER BY mid");
		while ($field = $db->fetch_array($rs)) {
			$fielddb[$field['mid']][$field['fid']] = $field;
		}
		foreach ($mids as $mid){
			if($mid<1) continue;
			$fieldcache.="\t$mid => array(\n";
			foreach ($fielddb[$mid] as $fid=>$array){
				$fieldcache.="\t\t'$fid'=> array(\n";
				$fieldcache.=$this->getCache($array);
				$fieldcache.="\t\t),\n";
			}
			$fieldcache.="\t),\n";
		}
		$fieldcache.=");\n";
		writeover($this->cacheDir.'field.php',"<?php\n".$fieldcache."?>");
	}

	function singleCate($cid){ //对单一栏目生成缓存，避免频繁读取总的大缓存，一定程度缓解负载
		global $db;
		if(!$cid) return ;
		$cid = (int)$cid;
		$rs = $db->get_one("SELECT * FROM cms_category WHERE cid='$cid'");
		$cache = "<?php\n\$cateinfo = array(\n";
		if($catedb['link']){
			$catedb['listurl']=$catedb['link'];
		}else{
			if($catedb['listpub']){
				$catedb['listurl']=$very['htmdir'].'/'.$catedb['listurl'];
			}else{
				$catedb['listurl']='list.php?cid='.$catedb['cid'];
			}
		}
		$cache.=$this->getCache($rs);
		$cache.=");\n?>";
		writeover($this->cacheDir.'cate_'.$cid.'.php',$cache);
	}

	function delCate($cid){
		unlink($this->cacheDir.'cate_'.$cid.'.php');
		return ;
	}

	function face(){
		global $db;
		$cache = "<?php\n\$facedb=array(\n";
		$rs = $db->query("SELECT * FROM cms_commentface ORDER BY taxis DESC");
		while ($face = $db->fetch_array($rs)) {
			$cache.="'".$face['id']."'=>array(\n";
			$cache.=$this->getCache($face);
			$cache.="),\n";
		}
		$cache.=");\n?>";
		writeover($this->cacheDir.'face.php',$cache);
	}

	function select(){
		global $db;
		$cache = "<?php\n\$selectdb=array(\n";
		$rs = $db->query("SELECT * FROM cms_select");
		while ($s = $db->fetch_array($rs)) {
			$cache.="'$s[selectid]'=>array(\n";
			$cache.="\t'selectid'=>'$s[selectid]',\n";
			$cache.="\t'selectname'=>'".addslashes($s['selectname'])."',\n";
			$cache.="),\n";
		}
		$cache.=");\n?>";
		writeover($this->cacheDir.'select.php',$cache);
	}

	/**
	 * 倘若一个缓存类没有被实例化，被静态调用时，则使用此方法
	 *
	 * @param string $cachetype
	 */
	function writeCache($cachetype){
		$cache = new Cache();
		$cache->$cachetype();
	}

	/**
	 * 根据数组来格式化缓存内容
	 *
	 * @param Array $array
	 * @return String
	 */
	function getCache($array){
		$cache = '';
		foreach ($array as $key=>$value){
			!is_numeric($value) && $value = addslashes($value);
			$cache.="\t'$key'=>'$value',\n";
		}
		return $cache;
	}

	/**
	 * 保存数组
	 *
	 * @param array $array
	 * @param string $index
	 */
	public function saveArray($array, $index, $pk = '')
	{
		//此处变量名全部小写化
		$index = strtolower($index);
		$this->cacheString .= "\$$index = array(\n";
		$this->arrToString($array, $pk);
		$this->cacheString .= ");\n\n";
	}

	/**
	 * 数组转化为需要的缓存格式
	 *
	 * @param array $array
	 */
	protected function arrToString($array, $pk = '')
	{
		foreach ($array as $key => $value)
		{
			if (is_array($value)) {
				$this->depth ++;
				if (!empty($pk) && isset($array[$key][$pk])) $key = $array[$key][$pk];
				$this->cacheString .= str_repeat("\t", $this->depth) . "'$key' => array(\n";
				$this->arrToString($value);
				$this->depth --;
				$this->cacheString .= str_repeat("\t", $this->depth + 1) . "),\n";
			} else {
				$value = addslashes($value);
				$this->cacheString .= str_repeat("\t", $this->depth + 1) . "'$key' => '$value',\n";
			}
		}
	}


	function nav(){
		global $db;
		$rs=$db->query("select * from cms_nav order by view DESC");
		$nav_head=$nav_foot=array();
		while ($navdb=$db->fetch_array($rs)){
			if($navdb['pos']=='foot'){
				$nav_foot[]=$navdb;
			}elseif ($navdb['pos']=='head'){
				$nav_head[]=$navdb;
			}
		}
		$navdb = $navinfo = array();
		$writemsg="<?php\n";
		$writemsg.=$this->writeVar('nav_head',$nav_head);
		$writemsg.=$this->writeVar('nav_foot',$nav_foot);
		foreach ($nav_head as $navdb){
			$target = $navdb['target']==1 ? '_blank' : '_self';
			$style_array=explode('|',$navdb['style']);
			$style_array[1] && $navdb['title']='<b>'.$navdb['title'].'</b>';
			$style_array[2] && $navdb['title']='<i>'.$navdb['title'].'</i>';
			$style_array[3] && $navdb['title']='<u>'.$navdb['title'].'</u>';
			$style_array[0] && $navdb['title']="<font color=\"$style_array[0]\">".$navdb['title']."</font>";
			$navinfo[] = "<li><a href=\"".$navdb['link']."\" target=\"".$target."\" title=\"".$navdb['alt']."\">".$navdb['title']."</a></li>";
		}
		$navinfo_h = implode(' ',$navinfo);
		$navinfo = array();
		foreach ($nav_foot as $navdb){
			$target = $navdb['target']==1 ? '_blank' : '_self';
			$style_array=explode('|',$navdb['style']);
			$style_array[1] && $navdb['title']='<b>'.$navdb['title'].'</b>';
			$style_array[2] && $navdb['title']='<i>'.$navdb['title'].'</i>';
			$style_array[3] && $navdb['title']='<u>'.$navdb['title'].'</u>';
			$style_array[0] && $navdb['title']="<font color=\"$style_array[0]\">".$navdb['title']."</font>";
			$navinfo[] = "<li><a href=\"".$navdb['link']."\" target=\"".$target."\" title=\"".$navdb['alt']."\">".$navdb['title']."</a></li>";
		}
		$navinfo_f = implode(' ',$navinfo);
		$writemsg.="\$navhead =\"".addslashes($navinfo_h)."\";\n";
		$writemsg.="\$navfoot =\"".addslashes($navinfo_f)."\";\n";
		$writemsg.='?>';
		writeover($this->cacheDir.'nav.php',$writemsg);
	}

	function writeVar($varname,$arrayvalue){
		$msg="\$$varname=array(\n";
		$i=0;
		foreach ($arrayvalue as $v){
			$i++;
			$msg.="\t'$i'=>array(\n";
			foreach ($v as $key=>$val) {
				$val=addslashes($val);
				$msg.="\t\t'$key'\t=>'$val',\n";
			}
			$msg.="\t),\n";
		}
		$msg.=");\n";
		return $msg;
	}

	function jsCache($adpinfo,$advinfo){
		global $db;
		$jscode = '';
		$zoneAD = "ZoneAD_{$adpinfo[pid]}";
		if($adpinfo['type'] == 'banner'){
			$jscode = readover(D_P.'script/adBanner.js');
			$jscode .= "
var {$zoneAD} = new BannerZoneAD(\"$zoneAD\");
{$zoneAD}.ZoneID      = $adpinfo[pid];
{$zoneAD}.ZoneWidth   = $adpinfo[width];
{$zoneAD}.ZoneHeight  = $adpinfo[height];
{$zoneAD}.ShowType    = $adpinfo[showtype];
{$zoneAD}.Active      = $adpinfo[active];
";
		} elseif($adpinfo['type'] == 'fixed'){
			$jscode = readover(D_P.'script/adFixed.js');
			$jscode .= "
var {$zoneAD} = new FixedZoneAD(\"$zoneAD\");
{$zoneAD}.ZoneID      = $adpinfo[pid];
{$zoneAD}.ZoneWidth   = $adpinfo[width];
{$zoneAD}.ZoneHeight  = $adpinfo[height];
{$zoneAD}.ShowType    = $adpinfo[showtype];
{$zoneAD}.Left        = {$adpinfo[setting][left]};
{$zoneAD}.Top         = {$adpinfo[setting][top]};
{$zoneAD}.Active      = $adpinfo[active];
";
		} elseif($adpinfo['type'] == 'pop'){
			$jscode = readover(D_P.'script/adPop.js');
			$jscode .= "
var {$zoneAD} = new PopZoneAD(\"$zoneAD\");
{$zoneAD}.ZoneID      = $adpinfo[pid];
{$zoneAD}.ZoneWidth   = $adpinfo[width];
{$zoneAD}.ZoneHeight  = $adpinfo[height];
{$zoneAD}.ShowType    = $adpinfo[showtype];
{$zoneAD}.Left        = {$adpinfo[setting][left]};
{$zoneAD}.Top         = {$adpinfo[setting][top]};
{$zoneAD}.PopType     = {$adpinfo[setting][poptype]};
{$zoneAD}.CookieHour  = {$adpinfo[setting][cookiehour]};
{$zoneAD}.Active      = $adpinfo[active];
";
		} elseif($adpinfo['type'] == 'float'){
			$jscode = readover(D_P.'script/adFloat.js');
			$jscode .= "
var {$zoneAD} = new FloatZoneAD(\"$zoneAD\");
{$zoneAD}.ZoneID      = $adpinfo[pid];
{$zoneAD}.ZoneWidth   = $adpinfo[width];
{$zoneAD}.ZoneHeight  = $adpinfo[height];
{$zoneAD}.ShowType    = $adpinfo[showtype];
{$zoneAD}.Left        = {$adpinfo[setting][left]};
{$zoneAD}.Top         = {$adpinfo[setting][top]};
{$zoneAD}.floattype     = {$adpinfo[setting][floattype]};
{$zoneAD}.delay  = {$adpinfo[setting][delay]};
{$zoneAD}.Active      = $adpinfo[active];
";
		} elseif($adpinfo['type'] == 'move'){
			$jscode = readover(D_P.'script/adMove.js');
			$jscode .= "
var {$zoneAD} = new MoveZoneAD(\"$zoneAD\");
{$zoneAD}.ZoneID      = $adpinfo[pid];
{$zoneAD}.ZoneWidth   = $adpinfo[width];
{$zoneAD}.ZoneHeight  = $adpinfo[height];
{$zoneAD}.ShowType    = $adpinfo[showtype];
{$zoneAD}.Left        = {$adpinfo[setting][left]};
{$zoneAD}.Top         = {$adpinfo[setting][top]};
{$zoneAD}.floattype     = {$adpinfo[setting][floattype]};
{$zoneAD}.Delta  = {$adpinfo[setting][delta]};
{$zoneAD}.Active      = $adpinfo[active];
";
		} elseif($adpinfo['type'] == 'code'){
			$jscode = readover(D_P.'script/adCode.js');
			$jscode .= "
var {$zoneAD} = new CodeZoneAD(\"$zoneAD\");
{$zoneAD}.ZoneID      = $adpinfo[pid];
{$zoneAD}.Active      = $adpinfo[active];
";
		}

		foreach($advinfo as $value){
			$jscode .="
var objAD = new ObjectAD();
objAD.ADID           = $value[adid];
objAD.ADType         = $value[type];
objAD.ADName         = \"$value[name]\";
objAD.ImgUrl         = \"{$value[config][url]}\";
objAD.ImgWidth       = {$value[config][width]};
objAD.ImgHeight      = {$value[config][height]};
objAD.FlashWmode     = {$value[config][flashwmode]};
objAD.ADIntro        = \"$value[intro]\";
objAD.LinkUrl        = \"$value[linkurl]\";
objAD.LinkTarget     = $value[linktarget];
objAD.LinkAlt        = \"$value[linkalt]\";
objAD.Priority       = $value[priority];
objAD.CountView      = 0;
objAD.CountClick     = 0;
objAD.InstallDir     = \"/\";
objAD.ADDIR          = \"\";
objAD.StartTime      = $value[starttime];
objAD.EndTime        = $value[endtime];
objAD.Cid			 = \"$value[cid]\";
{$zoneAD}.AddAD(objAD);
";
		}
		$jscode .= "{$zoneAD}.Show();";
		writeover(D_P.'script/verycms/'.$adpinfo['jsname'].'.js',$jscode);
	}

	function sql($setting=array()){
		global $db;
		require GetLang('dbset');
		include D_P.'data/sql_config.php';

		empty($pconnect) && $pconnect=0;

		if($setting && is_array($setting)){
			$setting['user'] && $manager = $setting['user'];
			$setting['pwd'] && $manager_pwd = $setting['pwd'];
		}
		$modulearray='';
		$rs = $db->query("SELECT * FROM cms_module");
		while ($mod = $db->fetch_array($rs)) {
			$modinfo[$mod['mid']] = $mod;
		}
		/*
		$modinfo['-2'] = array(
		'mid'=>'-2',
		'mname'=>"$lang[modbbs]",
		);
		$modinfo['-1'] = array(
		'mid'=>'-1',
		'mname'=>"$lang[modblog]",
		);
		*/
		foreach($modinfo as $key=>$value){
			$modulearray.="\t'$key'=>array(\n";
			foreach($value as $k => $val){
				$val = addslashes($val);
				$modulearray.="\t\t'$k'=>'$val',\n";
			}
			$modulearray.="\t),\n";
		}

		$writetofile=
		"<?php
/**
* $lang[info]
*/
\$dbhost\t\t=\t'$dbhost';\t\t// $lang[dbhost]
\$dbuser\t\t=\t'$dbuser';\t\t// $lang[dbuser]
\$dbpw\t\t=\t'$dbpw';\t\t// $lang[dbpw]
\$dbname\t\t=\t'$dbname';\t\t// $lang[dbname]
\$database\t=\t'mysql';\t\t// $lang[database]
\$_pre\t\t=\t'$_pre';\t\t// $lang[PW]
\$pconnect\t=\t'$pconnect';\t\t//$lang[pconnect]

/*
$lang[charset]
*/
\$charset\t\t=\t\t'$charset';

/**
* $lang[ma_info]
*/
\$manager\t\t=\t\t'$manager';\t\t//$lang[manager_name]
\$manager_pwd\t=\t\t'$manager_pwd';\n//$lang[manager_pwd]

/**
* $lang[module]
*/
\$moduledb=array(
$modulearray
);
".'?>';
		writeover(D_P.'data/sql_config.php',$writetofile);
	}
}


function pw_var_export($array,$c=1,$t='',$var=''){
	$c && $var="array(\r\n";
	$t.="\t";
	if(is_array($array)){
		foreach($array as $key => $value){
			$var.="$t'".str_replace(array("\\","'"),array("\\\\","\'"),$key)."'=>";
			if(is_array($value)){
				$var.="array(\r\n";
				$var=pw_var_export($value,0,$t,$var);
				$var.="$t),\r\n";
			} else{
				$var.="'".str_replace(array("\\","'"),array("\\\\","\'"),$value)."',\r\n";
			}
		}
	}
	if($c){
		$var.=")";
	}
	return $var;
}

function db_cv($array){
	if(is_array($array)){
		foreach($array as $key=>$value){
			$array[$key]=str_replace(array("\\","'"),array("\\\\","\'"),$value);
		}
	}
	return $array;

}
function key_cv($key){
	$key = str_replace(
	array(';','\\','/','(',')','$'),
	'',
	$key
	);
	return $key;
}
?>